<?php
declare (strict_types = 1);

namespace app\admin\middleware;

use app\admin\model\AdminUser;
use think\Request;
use think\Response;

/**
 * 登录中间件
 * Class LoginCheck
 * @package app\admin\middleware
 */
class LoginCheck
{

    /**
     * 不需要登陆页面
     * @var array
     */
    protected $noLogin = ['login/index','common'];
    protected $loginPath = ['login/index','login/loginform'];
    protected $urlPath;

    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response $response
     */
    public function handle(Request $request, \Closure $next) : Response
    {
        $response = $next($request);
        $this->urlPath = $request->controller(true).'/'.$request->action(true);

            if(!AdminUser::hasLogin()){
                if(!AdminUser::loginRemember()){
                    if(!$this->noLogin($request)){
                        if($request->isAjax()){
                            return json('login');
                        }
                        return redirect('/login/index');
                    }
                }
            }
        //已经登录过 访问登录页跳转到首页
        if(AdminUser::hasLogin()){
            if(in_array($this->urlPath,$this->loginPath)){
                return redirect('/index/index');
            }
        }
        return $response;
    }

    /**
     * 判断不需要登陆
     * @return bool  true : 不需要登陆 false 需要登陆
     */
    private function noLogin(Request $request):bool{
        return in_array($this->urlPath,$this->noLogin) || $request->controller(true) == 'common';
    }
}
